/********************************************************************
 *
 *  fmm_draw_labels.cpp
 *
 *  Draw labels for a FMM model
 *
 *  Created by Dahua Lin, on Nov 15, 2010
 *
 ********************************************************************/

#include <mex.h>

#include "psample_base.h"

using namespace ddp;


void draw_labels(int K, int n, const double *LPri, const double *LLik, 
        const double *u, double *s)
{
    double *pos = new double[K];
    double *F = new double[K];
    
    const double *llik = LLik;
    
    for (int i = 0; i < n; ++i)
    {
        calc_posterior(K, LPri, llik, pos);            
        s[i] = dsample(K, pos, u[i], F) + 1; // in matlab, it is one-based
        
        llik += K;
    }
    
    delete[] pos;
    delete[] F;
}




/**
 * main entry
 *
 * Input:
 *   [0]: LPri:     the log-prior probabilities of components [K x 1 double]
 *   [1]: LLik:     the log-likelihood values [K x n double]
 *   [2]: u:        values randomly drawn from uniform distr. [1 x n double]
 * 
 * Output:
 *   [0]: s:        the obtained samples
 */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // take input
    
    const mxArray *mxLPri = prhs[0];
    const mxArray *mxLLik = prhs[1];
    const mxArray *mxU = prhs[2];
    
    int K = (int)mxGetM(mxLLik);
    int n = (int)mxGetN(mxLLik);
    
    const double *LPri = mxGetPr(mxLPri);
    const double *LLik = mxGetPr(mxLLik);
    const double *u = mxGetPr(mxU);
    
    // prepare output
    
    mxArray *mxS = mxCreateDoubleMatrix(n, 1, mxREAL);
    double *s = mxGetPr(mxS);
    
    // main
    
    draw_labels(K, n, LPri, LLik, u, s);
    
    plhs[0] = mxS;
    
}


